<template>
  <div class="upload">
    <el-card>
      <h2>员工导入</h2>
      <!-- beforeUpload上传前的:方法返回boolean值,它可以定义解析excel前的限制条件,比如文件大小,太大不解析-->
      <!-- onSuccess上传后解析 拿到解析后的回调函数 -->
      <excal :before-upload="beforeUpload" :on-success="onSuccess" />
    </el-card>
  </div>
</template>

<script>
import excal from '@/components/libs/excal.vue'
import moment from 'moment'
import { sysuserbatch } from '@/api/employees.js'
export default {
  components: {
    excal
  },
  methods: {
    beforeUpload(file) {
      return true
    },

    async  onSuccess(obj) {
      const rule = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      const newObj = {}
      //   const newArr
      //   循环遍历数组results
      const newArr = obj.results.map(item => {
        Object.keys(item).forEach(item2 => {
          if (item2 === '转正日期' || item2 === '入职日期') {
            item[item2] = this.getExcalTime(item[item2])
            newObj[rule[item2]] = item[item2]
          } else {
            newObj[rule[item2]] = item[item2]
          }
        })
        return newObj
      })
      //   批量导入员工
      await sysuserbatch(newArr)
      //   导入成功-提示导入成功信息,返回员工列表页面
      this.$message.success('导入成功')
      this.$router.push('/employees')
      console.log(newArr)
    },
    // 转换表格中时间
    getExcalTime(num) {
      const t = new Date((num - 1) * 24 * 60 * 60 * 1000 - 8 * 60 * 60 * 1000)
      t.setYear(t.getFullYear() - 70)
      return moment(t).format('YYYY-MM-DD')
    }
  }

}
</script>

<style lang='scss' scoped>
h2{
    text-align: center;
}

</style>
